<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 * Default expertise form for viewing, modifying, adding, etc.
 *  
 * @package com_musashi
 * @author Daniel Torres
 */
 
// Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access. Sorry');
 
// Add the stylesheet for this page
JHTML::_('stylesheet','base.css','components/com_musashi/views/common/');
JHTML::_('script','dropdown.js','components/com_musashi/views/common/');
JHTML::_('stylesheet','expertise.css','components/com_musashi/views/expertise/tmpl/');
JHTML::_('script','dragdrop.js','components/com_musashi/views/expertise/tmpl/');

// Validate this page. This prevents unknown users from sending forms to our controller objects
$session =& JFactory::getSession();
$session->set('validFormCheck',true);

/**
 *  Checks to see if there is a message from a previous action. Clears the flag if necessary
 */
function getActionResult( $actionFlag )
{
    $session =& JFactory::getSession();
    
    // Get previous message, then clear
    $msg = $session->get($actionFlag,'');
    $session->set($actionFlag,'');
    
    return $msg;
}


// See if there were any errors from last operation
$lastUpdated = getActionResult('lastUpdated');
$lastError   = getActionResult('actionError');
$lastResult  = getActionResult('actionResult');

// We'll be needing this model
$model =& $this->getModel();


/**
 *  Helper function. Given a position id and an array of expertise data, looks
 *  through the information and returns the given expertise level of this user
 *  
 *  @param a_songPosition   A position ID for the currently analyzed song
 *  @param a_songExpertise  An array of [pos id, pos name, confort level] entries for a given user
 *  @return Expertise level, or lower expertise level if not found.
 */
function getExpertiseIDForPosition( $a_songPosition, $a_songExpertise )
{
    foreach ( $a_songExpertise as $expertise )
    {
        if( $expertise[0] == $a_songPosition )
        {
            return $expertise[2];
        }
    }
    
    return 0;    
}


?>
<script language="javascript" type="text/javascript">
<!--

// Changes the value of an experience entry
function selectExperience(control, positionIndex )
{
    //alert("Selecting value: "+control.value+" on form "+control.form.id+" at position index " + positionIndex);
    
    // Set val[positionIndex] = selected option
    inputObj       = control.form.elements["val["+positionIndex+"]"];
    inputObj.value = control.value;    
}

// Make sure you don't delete a song's entry by accident
function confirmDeletion( songName )
{
    return confirm("Removing "+songName+", are you sure?");
}

// Changes the value of the dropdown toggle link
function switchLabel(toggleObject,controlName)
{
    var labelObj = document.getElementById(controlName);
    if (labelObj.style.display == 'block'){
        toggleObject.innerHTML = 'Close';
    } else {
        toggleObject.innerHTML = 'Modify';
    }
}


-->
</script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->

<musashiContent id="content" class="body">
    
    <header id="title" class="body">
        <div class="name">
            <h1>Your Song Expertise</h1>
        </div>
        <div class="description">
            <p>These are the songs you can play. Each one must have at least one
            playable position. For each song, indicate the position(s) you feel
            confortable with, as well as the level of proficiency or ability.</p>
        </div>
    </header>
    
    <?php
    // If there was any error from last attempt, display it here
    if ($lastError != ""){ ?>
        <div class="error">Failed to add song! Please try again, or report this problem ("<?php echo $lastError; ?>)"</div>
        <?php
    }
    
    // Action result
    if($lastResult != "") {
        echo '<div class="result">'.$lastResult.'</div>';
    }
    ?>
    <div id="song-selector">
        <div class="known-songs" id="song-container">
            <h1>Known songs</h1>
            <h2>Drag and drop available songs from the right into this box</h2>
            <div class="known-songs-container" id="song-drop-target">
                <?php
                // -------------------------------------------------------------------------
                // Songs we know already
                // -------------------------------------------------------------------------
                
                $knownSongs = $model->getKnownSongs();
                
                // For each song, obtain:
                // a) Positions,
                // b) Our position rating
                if( $knownSongs )
                {
                    foreach( $knownSongs as $songEntry )
                    {
                        // The random number prevents joomla from caching this operation. We would disable caching altogether for this instead, but since
                        // this option won't be used that frequently, we don't care.
                        $removeLink = JRoute::_('index.php?option=com_musashi&controller=expertise&task=removeExpertise&songid='.$songEntry[0].'&rn='.rand(1,9999),false);
                        
                        // If we are editing this song, keep it open. Otehrwise, close it
                        if ($songEntry[0] == $lastUpdated)  {
                            $displayStyle = 'display:block;';
                            $toggleText   = 'Close';
                        } else {
                            $displayStyle = 'display:none;';
                            $toggleText   = 'Modify';
                        }
                        
                        // Id used for the params of this element
                        $paramID = $songEntry[0].'-params';
                        
                        ?>
                        <div class="song-entry" id="<?php echo $songEntry[0]; ?>" draggable="true" ondragstart="onStartDragging(event)" ondragend="onStopDragging(event)"  >
                            <h3><?php echo $songEntry[1]; ?></h3>
                            <ol>
                                <li><a href="<?php echo  $removeLink; ?>" onclick="return confirm('Removing '+'<?php echo $songEntry[1]; ?>'+', are you sure?');">Delete</a></li>
                                <li><a href="#" onclick="toggleSectionByID('<?php echo $songEntry[0]; ?>','<?php echo $paramID; ?>', false); switchLabel(this,'<?php echo $paramID; ?>')"><?php echo $toggleText; ?></a></li>
                            </ol>
                            <form id="song-form" method="post" action="<?php echo JRoute::_('index.php'); ?>" >                      
                                <ol id="<?php echo $paramID; ?>" style="<?php echo $displayStyle; ?>">
                                <?php
                                    // This song's positions and expertise for the current user
                                    // These are separate because there might be new positions
                                    // for which we haven't registered expertise.
                                    
                                    $songPositions = $model->getSongPositions( $songEntry[0] );
                                    $songExpertise = $model->getSongExpertise( $songEntry[0] );
                                    $counter       = 0;
                                    foreach( $songPositions as $position )
                                    {
                                        $expertiseID = getExpertiseIDForPosition($position[1], $songExpertise); ?>
                                        <li>
                                            <label><?php echo $position[0]; ?></label>
                                            <select name="pos_<?php echo $position[1]; ?>" onchange="selectExperience(this,<?php echo $counter; ?>);" >
                                                <?php echo $model->getConfortHTMLCombo( $expertiseID ); ?>
                                            </select>
                                            <input type="hidden" name="pos[<?php echo $counter; ?>]" value="<?php echo $position[1]; ?>" /> 
                                            <input type="hidden" name="val[<?php echo $counter; ?>]" value="<?php echo $expertiseID; ?>" />
                                        </li>
                                        <?php
                                        $counter ++;
                                    }
                                    ?>
                                    <li>
                                        <input type="submit" name="submit" value="Update information" />
                                    </li>
                                </ol>                                
                                <input type="hidden" name="songid" value="<?php echo $songEntry[0]; ?>" />
                                <input type="hidden" name="posCount" value="<?php echo count($songPositions); ?>" />
                                <input type="hidden" name="option" value="com_musashi" />
                                <input type="hidden" name="task" value="updateSongExpertise" />
                                <input type="hidden" name="controller" value="expertise" />                                
                            </form>
                        </div>
                        <?php
                    }
                }
                
                // ...
                
                ?>
            </div>
        </div>
        
        <div class="available-songs">
            <h1>Available songs</h1>
            <div class="available-songs-container"  >
                <?php
                
                // -------------------------------------------------------------------------
                // Songs we don't know yet
                // -------------------------------------------------------------------------
                $unknownSongs = $model->getUnknownSongs();
                foreach( $unknownSongs as $songEntry )
                {
                    // a) Song id
                    // b) Song name
                    $thisUpdate = JRoute::_('index.php?option=com_musashi&controller=expertise&task=addSong&songid='.$songEntry[0]);
                    ?>
                    <form class="song-entry" id="<?php echo $songEntry[0]; ?>" draggable="true"
                                                       ondragstart="onStartDragging(event)"
                                                       ondragend="onStopDragging(event)"
                                                       method="post"
                                                       action="<?php echo $thisUpdate; ?>"
                                                       >
                        <h3><?php echo $songEntry[1]; ?></h3>
                    </form>
                    <?php                    
                }?>
            </div>
        </div>
    </div>
    
    <!-- Footer. Display syndication, and some copyright information -->
    <footer id="footer" class="body">
        <div class="footer-data">
            <h2>The Musashi Project</h2>
            <h3>A Framework for Managing Your Group</h3>
            <p>(c)2010 - The Musashi Project</p>                    
        </div>
    </footer>
    
</musashiContent>
